package com.springboot.demo.model.util;

import cn.hutool.core.util.StrUtil;
import com.springboot.demo.model.constants.SunMiniappRedisConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 阳光大姐微信小程序工具类
 * Created by hwm on 2018/7/13.
 */
public class SunMiniappUtil {

    private static Logger log = LoggerFactory.getLogger(SunMiniappUtil.class);

    /**
     * 验证是否重复请求
     *
     * @param prefixKey     前缀key
     * @param redisTemplate
     * @param httpRequest
     * @param httpResponse
     * @return 重复请求返回true，否则false
     * @throws ServletException
     * @throws IOException
     */
    public static boolean validateRepeatRequest(String prefixKey, StringRedisTemplate redisTemplate, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {

        // 登陆用户token
        String tokenStr = httpRequest.getHeader(SunMiniappRedisConstants.CUSTOMER_HEAD_TOKEN_KEY);

        // 过滤重复请求，每个token每个url，一秒之内只能请求一次，防止重复提交
        // 解决方案，拼装用户token+请求url，存入redis,每次请求判断redis该请求是否存在（有效时间一秒），如果存在，则重复提交，不做任何处理
        String filterUrl = StrUtil.format("{}_{}_{}", prefixKey, tokenStr, httpRequest.getRequestURI());
        // 缓存请求信息到redis
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(filterUrl, httpRequest.getRequestURI());
        if (aBoolean) {
            // 设置成功，设置key缓存时间，有效时间一秒
            try {
                redisTemplate.expire(filterUrl, 1, TimeUnit.SECONDS);
            } catch (Exception e) {
                redisTemplate.delete(filterUrl);
            }
        } else {
            log.debug("============================重复请求，不予处理===========================");
            log.debug("============================重复请求，不予处理===========================");
            log.debug("============================重复请求，不予处理===========================");
            httpRequest.getRequestDispatcher("/comm/repeatRequest").forward(httpRequest, httpResponse);
            return true;
        }
        return false;
    }

}
